﻿using System.Collections.Generic;
using UnityEngine;

namespace GameCore
{
    public class GameObjectPool : SingletonWhereMono<GameObjectPool>
    {
        Dictionary<string, List<GameObject>> pool;

        public void PushInPool(GameObject obj)
        {
            AssetFlag flag = obj.GetComponent<AssetFlag>();
            if(flag != null)
            {
                string key = flag.Path;
                if (!pool.ContainsKey(key))
                {
                    pool.Add(key, new List<GameObject>());
                }
                pool[key].Add(obj);
                obj.transform.parent = transform;
            }
            else
            {
                Destroy(flag);
            }
        }

        public GameObject PullOutPool(string key)
        {
            if (pool.ContainsKey(key))
            {
                List<GameObject> objs = pool[key];
                int count = objs.Count;
                if(objs.Count > 0)
                {
                    GameObject target = objs.Back();
                    objs.RemoveAt(count - 1);
                    return target;
                }
            }
            return null;
        }

        private void Clear()
        {
            foreach(List<GameObject> objList in pool.Values)
            {
                while (objList.Count > 0)
                {
                    if(objList[0] != null)
                    {
                        Destroy(objList[0]);
                    }
                    
                    objList.RemoveAt(0);
                }
            }
            pool.Clear();
        }

        private void Awake()
        {
            pool = new Dictionary<string, List<GameObject>>();
            
            
        }

        private void OnDestroy()
        {
            Clear();
            pool = null;
        }
    }

}